<?
class Handler {
	/***********************************
	 *           PASSWORD
	 ***********************************/
	private $mysql_password = "****";
	/***********************************
	 *      CONFIGURATION FILES
	 ***********************************/
	private $xml_conf = "conf/conf.xml";
	private $xml_conf_backup = "conf/conf_backup.xml";
	private $xml_error = "conf/error.xml";
	private $xml_recover = "conf/recover.xml";
	private $log = "log/system.log";
	private $counter = "log/counter.log";
	
	
	
	/************************************
	 *  NO NEED TO MODIFY ANYTHING ELSE
	 * Check your 'conf.xml' for editing
	 * any configuration detail you want
	 ************************************/
	private $conn;
	private $philomousia;
	private $config;
	private $recover;
	private $path = "../";
	
	/*******************
	 *    PSEUDO-TAG
	 *******************/
	private $old = array("à", "è", "ì", "ò", "ù", "é");
	private $new = array("&agrave;", "&egrave;", "&igrave;", "&ograve;", "&ugrave;", "&eacute;");
	
	private $pseudo = array(
		"[b]", 		"[/b]",
		"[em]", 	"[/em]",
		"[u]", 		"[/u]",
		"[h]", 		"[/h]",
		"[d]", 		"[/d]",
		
		"[ulist]", 	"[/ulist]", 
		"[olist]", 	"[/olist]", 
		"[elem]", 	"[/elem]",
		
		"[left]", 	"[/left]", 
		"[right]", 	"[/right]", 
		"[center]",	"[/center]"
	);
	private $html = array(
		"<span class=\"bold\">", 		"</span>",
		"<span class=\"italic\">", 		"</span>",
		"<span class=\"underline\">", 	"</span>",
		"<span class=\"highline\">", 	"</span>",
		"<span class=\"delete\">", 		"</span>",
		
		"<ul>", 						"</ul>", 
		"<ol>", 						"</ol>", 
		"<li>", 						"</li>",
		
		"<div class=\"left\">", 		"</div>",
		"<div class=\"right\">", 		"</div>",
		"<div class=\"center\">",	 	"</div>"
	);
	
	private $pseudo_complex = array(
		"/\[img=(.+)\](.+)\[\/img\]/i",
		"/\[url=(.+)\](.+)\[\/url\]/i",
		"/\[color=(#[a-fA-F0-9]{6})\](.+)\[\/color\]/i",
		"/\[size=([1-3][0-9])\](.+)\[\/size\]/i",
		"/\[quote=(.+)\](.+)\[\/quote\]/i",
		"/\[youtube=(.+)\]http:\/\/(www|it)\.youtube\.com\/watch\?v\=(.+)(&(.+))?\[\/youtube\]/i"
	);
	private $html_complex = array(
		"<div class=\"content_image\"><img src=\"\\2\" alt=\"\\1\" /><p class=\"small italic caption\">\\1</p></div>",
		"<a href=\"\\1\">\\2</a>",
		"<span style=\"color:\\1\">\\2</span>",
		"<span style=\"font-size:\\1px\">\\2</span>",
		"<div class=\"quote_box\"><p class=\"quoted_text\">\\2</p><p class=\"author\">\\1</p></div>",
		"<div class=\"youtube\"><object width=\"300\" height=\"255\"><param name=\"movie\" value=\"http://www.youtube.com/v/\\3&hl=it&fs=1&color1=0x999999&color2=0xd5d5d5&border=1\"></param><param name=\"allowFullScreen\" value=\"true\"></param><embed src=\"http://www.youtube.com/v/\\3&hl=it&fs=1&color1=0x999999&color2=0xd5d5d5&border=1\" type=\"application/x-shockwave-flash\" allowfullscreen=\"true\" width=\"300\" height=\"255\"></embed></object><p class=\"small italic caption\">\\1</p></div>"
	);
	
	
	/**
	* Load all configuration details in XML
	*/
	public function __construct($path = NULL) {
		//error_reporting(0);
		if($path!=NULL) $this->path = $path;
		$this->config = simplexml_load_file($this->path.$this->xml_conf);
		$this->recover = simplexml_load_file($this->path.$this->xml_recover);
		if($this->config) {
			$this->database = $this->config->database;
			$this->philomousia = $this->config->philomousia;
		}
		setlocale(LC_ALL, $this->getSetLocale());
		$this->updateCounter();
		return ($this->config);
	}
	
	public function reloadXML($path = NULL) {
		if($path!=NULL) $this->path = $path;
		$this->config = simplexml_load_file($this->path.$this->xml_conf);
		if($this->config) {
			$this->database = $this->config->database;
			$this->philomousia = $this->config->philomousia;
		}
		return ($this->config);
	}
	
	/**
	 * Start a connection with MySQL
	 */
	public function openDB($schema = NULL) {
		$dbhost = sprintf("%s:%s", $this->database->host, $this->database->port);
		$this->conn = mysql_connect($dbhost, $this->database->user, $this->mysql_password);
		if($this->conn) {
			if($schema!=NULL) $this->database->schema = $schema;
			mysql_select_db($this->database->schema);
		} else {
			$this->writeLog("[MYSQL ERROR] ".strftime("%c")." ".mysql_error()." from Class::Handler::openDB");
		}
		return $this->conn;
	}
	
	/**
	 * Select a database to use
	 */
	public function selectDB($schema) {
		if(mysql_select_db($this->schema)) {
			return true;
		} else {
			$this->writeLog("[MYSQL ERROR] ".strftime("%c")." ".mysql_error()." from Class::Handler::selectDB");
			return false;
		}
	}
	
	/**
	 * Delete all data from the specified table
	 */
	public function truncateTable($table) {
		$query = "TRUNCATE TABLE $table";
		if(mysql_query($query)) {
			return true;
		} else {
			$this->writeLog("[MYSQL ERROR] ".strftime("%c")." ".mysql_error()." from Class::Handler::truncateTable");
			return false;
		}
	}
	
	/**
	 * Reset data
	 */
	public function reset($post) {
		if($post["content"]) {
			$this->truncateTable("CONTENT");
		}
		if($post["comment"]) {
			$this->truncateTable("COMMENT");
		}
		if($post["tag"]) {
			$this->truncateTable("TAG");
		}
		if($post["content"] || $post["tag"]) {
			$this->truncateTable("CONTENT_TAG");
		}
		if($post["people"]) {
			$this->truncateTable("PEOPLE");
		}
		if($post["editorial"]) {
			$this->truncateTable("EDITORIAL");
		}
		if($post["link"]) {
			$this->truncateTable("LINK");
		}
		if($post["uploads"]) {
			$files = $this->getUploadedFiles();
			foreach($files as $key => $value) {
				$src = "../uploads/".basename($value);
				unlink($src);
			}
		}
		if($post["preferences"]) {
			$this->restorePreferences();
		}
		if($post["log"]) {
			file_put_contents($this->path.$this->log, "");
		}
		if($post["counter"]) {
			file_put_contents($this->path.$this->counter, 0);
		}
	}
	
	/**
	 * Close the connection with MySQL
	 */
	public function closeDB() {
		mysql_close($this->conn);
	}
	
	/**
	 * All getters of the configuration details
	 */
	
	public function getGMT() {
		return $this->philomousia->gmt;
	}
	
	public function getSetLocale() {
		return $this->philomousia->set_locale;
	}
	
	public function getLogLines() {
		return $this->philomousia->log_lines;
	}
	
	public function getDateFormat() {
		return $this->philomousia->date_format;
	}
	
	public function getHomeArticle() {
		return $this->philomousia->home_article;
	}
	
	public function showCalendar() {
		return $this->philomousia->show_calendar=="true";
	}
	
	public function allowComments() {
		return $this->philomousia->allow_comments=="true";
	}
	
	public function useSecurityImage() {
		return $this->philomousia->security_image=="true";
	}
	
	public function getPublicKey() {
		return $this->philomousia->public_key;
	}
	
	public function getPrivateKey() {
		return $this->philomousia->private_key;
	}
	
	public function getContentsPerPage() {
		return $this->philomousia->contents_per_page;
	}
	
	public function getIncipitChars() {
		return $this->philomousia->incipit_chars;
	}
	
	public function getBaseURL() {
		return $this->philomousia->base_url;
	}
	
	public function getAutocompleterResults() {
		return $this->philomousia->autocompleter_results;
	}
	
	public function getSearchNumChars() {
		return $this->philomousia->search_num_chars;
	}
	
	public function getMail() {
		return $this->philomousia->mail;
	}
	
	public function getTitle() {
		return $this->philomousia->title;
	}
	
	public function getSubtitle() {
		return $this->latinChars($this->cleanString($this->philomousia->sub_title));
	}
	
	public function getDescription() {
		return $this->latinChars($this->cleanString($this->philomousia->description));
	}
	
	public function getRecoverDelay() {
		return (int) $this->philomousia->recover_delay;
	}

	public function getUsername() {
		return $this->philomousia->username;
	}

	public function getPassword() {
		return $this->philomousia->password;
	}
	
	public function getRecoverTimestamp() {
		return $this->recover->timestamp;
	}
	
	public function getRecoverHash() {
		return $this->recover->hash;
	}
	
	public function cleanString($str) {
		$str = preg_replace("/\[\/quote\](\n)?(\r|\n)*/i", "[/quote]", $str);
		$str = preg_replace("/\[\/img\](\n)?(\r|\n)*/i", "[/img]", $str);
		$str = preg_replace("/(\n)?(\r|\n)*\[quote\]/i", "[quote]", $str);
		$str = preg_replace("/\[\/youtube\](\n)?(\r|\n)*/i", "[/youtube]", $str);
		$str = preg_replace("/\n\r(\n\r)+/", "\n\n", $str);
		$str = preg_replace("/\n\r/", "\n", $str);
		return strip_tags(htmlspecialchars(trim($str)));
	}
	
	public function makeHTML($str) {
		$str = preg_replace("/\n(\n)+/", "<br /><br />", $str);
		$str = str_replace("\n", "<br />", $str);
		$str = str_ireplace($this->pseudo, $this->html, $str);
		return preg_replace($this->pseudo_complex, $this->html_complex, $str);
	}
	
	public function latinChars($str) {
		return str_ireplace($this->old, $this->new, $str);
	}
	
	public function reverseString($str) {
		//$str = preg_replace("/\n(\n)+/", "\n\n", $str);
		$str = str_ireplace("[/quote]", "[/quote]\n\n", $str);
		$str = str_ireplace("[/img]", "[/img]\n\n", $str);
		//$str = str_ireplace("<br />", "", $str);
		//$str = str_ireplace($this->html, $this->pseudo, $str);
		//return preg_replace($this->reverse_html_complex, $this->reverse_pseudo_complex, $str);
		return strip_tags($str);
	}
	
	public function isImage($file) {
		$exts = split("[/\\.]", $file);
		$ext = $exts[count($exts)-1]; 
		return ($ext=="jpg" || $ext=="jpeg" || $ext=="gif" || $ext=="png" || $ext=="bmp");	
	}
	
	/**
	 * Fetch XML error file and return the specific error message
	 */
	public function getErrorMessage($error) {
		$file = simplexml_load_file($this->path.$this->xml_error);
		if($file) {
			$error = $file->xpath("error[type='$error']/message");
			return $error[0];
		} else {
			$this->writeLog("[XML ERROR] ".strftime("%c")." couldn't read xml error file from Class::Handler::getErrorMessage");
			return NULL;
		}
	}
	
	/**
	 * Restore original preference
	 */
	public function restorePreferences() {
		$data = file_get_contents($this->path.$this->xml_conf_backup);
		file_put_contents($this->path.$this->xml_conf, $data);
		return $this->reloadXML();
	}
	
	/**
	 * Save XML configuration data
	 */
	public function setNewPreferences($post) {
		$file = file_get_contents($this->path.$this->xml_conf);
		foreach($post as $key=>$value) {
			//[\w| |\%|\+|!|\?|,|\.|\/|@|:]
			$value = stripslashes($value);
			$file = preg_replace("/<$key>(.+)<\/$key>/i", "<$key>$value</$key>", $file);
		}
		file_put_contents($this->path.$this->xml_conf, $file);
		return $this->reloadXML();
	}
	
	/**
	 * Change password
	 */
	public function changePassword($hash) {
		$file = file_get_contents($this->path.$this->xml_conf);
		$file = preg_replace("/<password>([a-zA-Z0-9]+)<\/password>/i", "<password>$hash</password>", $file);
		return file_put_contents($this->path.$this->xml_conf, $file);
	}
	
	/**
	 * Write recover data
	 */
	public function writeRecover($hash, $time) {
		$file = file_get_contents($this->path.$this->xml_recover);
		$file = preg_replace("/<timestamp>([0-9]+)<\/timestamp>/i", "<timestamp>$time</timestamp>", $file);
		$file = preg_replace("/<hash>([a-zA-Z0-9]+)<\/hash>/i", "<hash>$hash</hash>", $file);
		return file_put_contents($this->path.$this->xml_recover, $file);
	}
	
	/**
	 * Update counter
	 */
	public function updateCounter() {
		$total = file_get_contents($this->path.$this->counter);
		$total = ((int)$total)+1;
		return file_put_contents($this->path.$this->counter, $total);
	}
	
	/**
	 * Counter
	 */
	public function getCounter() {
		return file_get_contents($this->path.$this->counter);
	}
	
	/**
	 * Write a new line in log
	 */
	public function writeLog($line) {
		return file_put_contents($this->path.$this->log, $line."\n", FILE_APPEND);
	}
	
	/**
	 * Print log out
	 */
	public function getLog() {
		return trim(file_get_contents($this->path.$this->log));
	}
	
	/**
	 * Get uploaded files
	 */
	public function getUploadedFiles() {
		$files = array();
		if($handle = opendir('../uploads')) {
			while(false!==($file = readdir($handle))) {
				if(substr($file, 0, 1)!=".") {
					$files[] = 'http://'.$_SERVER['SERVER_NAME'].$this->getBaseURL().'uploads/'.$file;
				} 
			}
			closedir($handle); 
		} else {
			$this->writeLog("[SYSTEM ERROR] ".strftime("%c")." couldn't read uploads directory from Class::Handler::getUploadedFiles");
		}
		sort($files);
		return $files;
	}
	
	/**
	 * Get years of activity
	 */
	public function getYears($start = "2008") {
		$years = $start;
		$now = strftime("%Y");
		if((int)$now>(int)$start) {
			$years .= " - ".$now;
		}
		return $years;
	}
	
	/**
	 * Check whether the specified image url is still valid 
	 */
	public function hasHTTPError($url) {
		$curl_handle = curl_init();
		curl_setopt($curl_handle, CURLOPT_URL, $url);
		curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl_handle, CURLOPT_FAILONERROR, true);
		curl_exec($curl_handle);
		return (curl_errno($curl_handle)>0);
	}
	
}
?>